package client.main.login;

import client.common.dto.LoginReqDTO;
import client.common.result.Result;
import client.main.choose.AdminChoose;
import client.main.menu.MainMenu;
import remote.common.storage.TokenStorage;
import remote.service.UserService;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

public class AdminLogin extends JFrame {
    private JLabel usernameLabel;
    private JLabel passwordLabel;
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JButton loginButton;
    private JButton backButton;
    private UserService userService = new UserService() {
    };
    
    public AdminLogin() {
        setTitle("管理员登录界面");
        setSize(800, 600);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(false);
        String path = System.getProperty("user.dir");
        String imageAbsolutePath = path + "\\background\\image.jpg";
        System.out.println("imageAbsolutePath: " + imageAbsolutePath);
        
        // 设置背景面板
        BackgroundPanel backgroundPanel = new BackgroundPanel(imageAbsolutePath); // 设置背景图片路径
        backgroundPanel.setLayout(new BoxLayout(backgroundPanel, BoxLayout.Y_AXIS)); // 垂直布局
        
        // 创建标题标签
        JLabel titleLabel = new JLabel("管理员登录");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 36));
        titleLabel.setForeground(Color.BLACK);
        titleLabel.setAlignmentX(Component.CENTER_ALIGNMENT); // 标题居中
        
        // 创建输入面板
        JPanel inputPanel = new JPanel();
        inputPanel.setOpaque(false);
        inputPanel.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10); // 增加组件之间的间距
        gbc.fill = GridBagConstraints.HORIZONTAL;
        
        // 用户名标签
        usernameLabel = new JLabel("管理员用户名：");
        usernameLabel.setFont(new Font("微软雅黑", Font.PLAIN, 24));
        usernameLabel.setForeground(Color.BLACK);
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.EAST;
        inputPanel.add(usernameLabel, gbc);
        
        // 用户名输入框
        usernameField = new JTextField(20);
        usernameField.setFont(new Font("微软雅黑", Font.PLAIN, 24));
        usernameField.setOpaque(false); // 设置透明
        usernameField.setBorder(BorderFactory.createLineBorder(Color.BLACK)); // 添加边框以便可见
        gbc.gridx = 1;
        gbc.anchor = GridBagConstraints.WEST;
        inputPanel.add(usernameField, gbc);
        
        // 密码标签
        passwordLabel = new JLabel("密码：");
        passwordLabel.setFont(new Font("微软雅黑", Font.PLAIN, 24));
        passwordLabel.setForeground(Color.BLACK);
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.anchor = GridBagConstraints.EAST;
        inputPanel.add(passwordLabel, gbc);
        
        // 密码输入框
        passwordField = new JPasswordField(20);
        passwordField.setFont(new Font("微软雅黑", Font.PLAIN, 24));
        passwordField.setOpaque(false); // 设置透明
        passwordField.setBorder(BorderFactory.createLineBorder(Color.BLACK)); // 添加边框以便可见
        gbc.gridx = 1;
        gbc.anchor = GridBagConstraints.WEST;
        inputPanel.add(passwordField, gbc);
        
        // 登录按钮
        loginButton = createSmallOvalButton("登录");
        gbc.gridy = 2;
        gbc.gridx = 0;
        gbc.gridwidth = 1;
        inputPanel.add(loginButton, gbc);
        
        // 添加登录按钮点击事件
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                login(); // 调用登录方法
            }
        });
        
        // 返回主菜单按钮
        backButton = createSmallOvalButton("返回主菜单");
        gbc.gridy = 3;
        inputPanel.add(backButton, gbc);
        
        // 添加返回按钮点击事件
        backButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                SwingUtilities.invokeLater(() -> {
                    new MainMenu().setVisible(true); // 返回主菜单
                    AdminLogin.this.dispose(); // 关闭当前窗口
                });
            }
        });
        
        // 添加组件到背景面板
        backgroundPanel.add(Box.createVerticalGlue()); // 添加垂直填充，保持组件在中间
        backgroundPanel.add(titleLabel);
        backgroundPanel.add(Box.createRigidArea(new Dimension(0, 40))); // 标题与输入面板之间的间距
        backgroundPanel.add(inputPanel);
        backgroundPanel.add(Box.createVerticalGlue()); // 添加垂直填充，保持组件在中间
        
        setContentPane(backgroundPanel); // 设置背景面板为主内容面板
        setVisible(true);
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(AdminLogin::new);
    }
    
    // 创建小椭圆形样式的按钮
    private JButton createSmallOvalButton(String text) {
        JButton button = new JButton(text) {
            @Override
            protected void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setColor(getBackground());
                g2.fillOval(0, 0, getWidth(), getHeight());
                super.paintComponent(g2);
                g2.dispose();
            }
            
            @Override
            protected void paintBorder(Graphics g) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setColor(new Color(48, 63, 159)); // 边框颜色
                g2.setStroke(new BasicStroke(3)); // 边框宽度
                g2.drawOval(0, 0, getWidth() - 1, getHeight() - 1);
                g2.dispose();
            }
        };
        button.setFont(new Font("微软雅黑", Font.BOLD, 18)); // 设置字体
        button.setBackground(new Color(63, 81, 181)); // 设置按钮背景色
        button.setForeground(Color.WHITE); // 设置按钮文本颜色
        button.setFocusPainted(false); // 去掉焦点边框
        button.setContentAreaFilled(false); // 去掉按钮填充
        button.setOpaque(false); // 设置为透明
        button.setPreferredSize(new Dimension(120, 40)); // 设置按钮大小
        button.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20)); // 增加按钮内边距
        return button;
    }
    
    // 登录方法
    private void login() {
        String username = usernameField.getText();
        String password = new String(passwordField.getPassword());
        
        // 构建登录请求参数
        LoginReqDTO requestParam = LoginReqDTO.builder()
                .phoneNumber(username)
                .password(password).build();
        
        try {
            // 发送登录请求
            Result<String> result = userService.login(requestParam);
            
            if (result.getCode() == 200) {
                // 登录成功，跳转到 Choose 界面
                SwingUtilities.invokeLater(() -> {
                    new AdminChoose().setVisible(true);
                    AdminLogin.this.dispose(); // 关闭当前窗口
                });
                String token = (String) result.getData();
                TokenStorage.setToken(token);
            } else {
                JOptionPane.showMessageDialog(this, "登录失败: 用户名或密码错误", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Throwable e) {
            JOptionPane.showMessageDialog(this, "登录失败: 无法连接到服务器", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    // 自定义背景面板类
    private static class BackgroundPanel extends JPanel {
        private Image backgroundImage;
        
        public BackgroundPanel(String imagePath) {
            try {
                backgroundImage = ImageIO.read(new File(imagePath));
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("背景图片加载失败！");
            }
        }
        
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (backgroundImage != null) {
                g.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), this);
            }
        }
    }
}
